var heroListJsonUrl = "data/heroinfo.json";
var horseListJsonUrl = "data/horseinfo.json";
var getEnableJsonUrl = "http://bfc.163.com/pc/fbyx_helper/enable.json";
var carouselUrl = "http://bfc.163.com/pc/fbyx_helper/carousel.html";

var jsGlobal = function() {
    this.color = [0];
    this.weekfree = [];
    this.talent = [];
    this.skill = [];
    this.recommend = [];
    this.enable = {};
    this.userEnable = {};
    this.currentPage = "shop";
    this.isGameRunning = false;
    this.isDownloadCompleted = false;

    this._init = function() {
        appGlobal.userEnable.enableHorse = HeroesApp.getConfig("web_enableHorse", "true");
        appGlobal.userEnable.enableTalents = HeroesApp.getConfig("web_enableTalent", "true");
        //app初始化
        window.myPageView = new pageView;
        Backbone.history.start();
        var msg = "1，新增免费商店功能||2，新增推荐天赋功能";
        // setTimeout(function() {
        // appGlobal.onUpdate(msg);
        // }, 1000);

        var handle = this;
        this._mountDefault = new window.horseList;
        this._talentDefault = new window.heroList;

        this._mountDefault.fetch();
        this._talentDefault.fetch({
            success : function() {
                //做初始化操作

                HeroesApp.ready();
                //传给后台ready消息
            }
        });

        //初始化enabel信息，默认为true
        this.enable.shop = HeroesApp.getConfig("web_shop_enable", "true");
        this.enable.talent = HeroesApp.getConfig("web_talent_enable", "true");

        //从服务器检查enabel信息
        setTimeout(function() {
            appGlobal._checkEnable();
        }, 1000)
    }

    this._checkInstall = function() {
        //检查是否安装游戏
        return HeroesApp.gameIsInstalled();
    }

    this.onGameStateChange = function(bRunning) {
        //alert("onGameStateChange:" + bRunning);
        appGlobal.isGameRunning = bRunning;
        if(bRunning) {
            $("#startButton").addClass("disabled");

            //如果正在更新
            if($("#update2_modal").hasClass("in")) {
                $("#update_gameRunning_modal").removeClass("out").addClass("in");
            }

        } else {
            $("#startButton").css({
                opacity : "1"
            }).removeClass("disabled").removeClass("starting");

            //如果正在更新,且显示update_gameRunning_modal
            if($("#update_gameRunning_modal").hasClass("in")) {
                $("#update_gameRunning_modal").removeClass("in").addClass("out");
                if(appGlobal.isDownloadCompleted) {//如果后台已经完成下载
                    appGlobal.onUpdateDownloading(100);
                }
            }

        }
    }

    this.onSetUserInfo = function(userName, iconIndex) {
        //alert("onRestoreSetting,userName:" + userName + ",iconIndex:" + iconIndex);
        $("#userName").text(userName);
        $("#userFace").attr("src", "img/face/" + iconIndex + ".jpg");

        HeroesApp.setConfig("web_userName", userName);
        HeroesApp.setConfig("web_userFace", iconIndex);
    }

    this.onSetting = function() {
        $("#mask").removeClass("none");
        $("#modal_option").removeClass("out").addClass("in");
    }

    this.onHeroChange = function(heroId) {
        var json;
        if(window.myHeroList == undefined) {
            console.log("window.myHeroList undefined")
            json = JSON.stringify(this._talentDefault.get(heroId));
        } else {
            console.log("window.myHeroList OK")
            json = JSON.stringify(window.myHeroList.get(heroId));
        }

        //判断用户设置是否可用
        //console.log(json)
        if(HeroesApp.getConfig("web_enableTalent", "true") == "true") {
            HeroesApp.setTalents(json);
        }
    }

    this.onUpdate = function(msg) {
        //初始化update1_modal
        msg = msg.split("||");

        $("#update1_modal .newFeature li").remove();
        for(var i in msg) {
            $("#update1_modal .newFeature").append($("<li>" + msg[i] + "</li>"))
        }

        $(".modal.in .close").trigger("click");
        $("#mask").removeClass("none");
        $("#update1_modal").addClass("in").removeClass("out");
    }

    this.onUpdateDownloading = function(percent) {
        if(!$("#update_gameRunning_modal").hasClass("in")) {
            $("#update2_modal .modal_foot .progressWrapper .expand").css({
                width : percent + "%"
            });
            $("#update2_modal .modal_foot .percent").text(percent + "%");
        }
        if(percent == 100) {

            //如果update_gameRunning_modal存在，则保存下载完成的状态
            //等游戏退出之后，再调用update3_modal
            if($("#update_gameRunning_modal").hasClass("in")) {
                appGlobal.isDownloadCompleted = true;
            } else {
                setTimeout(function() {
                    $("#update2_modal").addClass("out").removeClass("in");
                    $("#update3_modal").addClass("in").removeClass("out");
                }, 600);
            }

        }
    }

    this.onUpdateDownloadFail = function() {
        $("#update_error_modal").removeClass("out").addClass("in");
    }

    this.onBrowseDirectory = function(status) {
        if($.trim(status) == "cancel") {

        } else if($.trim(status) == "success") {
            appGlobal._init();
        } else {//error
            $("#not_install_img").attr("src", "img/not_install_error.png")
        }
    }

    this._show_first_shop_tips_modal = function() {
        //第一次开 免费商店 的指引
        $("#mask").removeClass("none");
        $("#first_shop_tips_modal").removeClass("out").addClass("in");

        $("#selectHorse ul li").addClass("first_tips");

        HeroesApp.setConfig("web_IsNotFirstTime_shop", "true")
    }

    this._show_first_talent_tips_modal = function() {
        //第一次开 天赋方案 的指引
        $("#mask").removeClass("none");
        $("#first_talent_tips_modal").removeClass("out").addClass("in");

        $("#mapList .mapWrapper:eq(0)").addClass("first_tips");

        HeroesApp.setConfig("web_IsNotFirstTime_talent", "true")
    }

    this._parseHeroTalents = function(data, recommend, userConfig) {
        //三个参数分别代表英雄json，该英雄推荐方案的数组，用户选择的推荐方案
        var talents = [];
        //userConfig = userConfig || "8,3,2,1,233";
        if(userConfig) {
            userConfig = userConfig.split(",");
        }

        for(var i = 1; i <= 5; i++) {// 5个地图的默认天赋
            var map = {};

            for(var j in recommend) {//对recommend遍历
                //如果有userConfig
                if(userConfig && userConfig[i - 1] != recommend[j]["TRID"]) {
                    continue;
                    // 与用户选择的方案不相同直接跳过
                }

                if(recommend[j]["Map"] == i) {//匹配到Mid
                    map = jQuery.extend(true, {}, recommend[j]);
                    for(var m = 0; m < 7; m++) {//7次加点
                        var n = m * 3 + 1;
                        //每3级加一次 点，从1级开始
                        n = n == 19 ? 20 : n;
                        //19级没有加点，20级才有

                        var index = (data["TIDLV" + n].split(",").indexOf(recommend[j]["LV" + n + "TID"].toString()) + 1).toString();
                        var name = appGlobal.talent[recommend[j]["LV"+n+"TID"] - 1]["Name"];
                        var icon = "data/Talent/t" + recommend[j]["LV" + n + "TID"] + ".png";
                        map["LV" + n + "TID"] = {
                            "index" : index,
                            "name" : name,
                            "icon" : icon
                        };

                    }
                    break;
                    //取recommend，MID第一次出现的为默认推荐方案
                }
            }
            talents.push(map);
        }
        return talents;
        //返回 "talents"字段数组
    }

    this._setTalents = function(hid, TRID) {
        //传入hid,与TRID，改变英雄的推荐方案
        var map = jQuery.extend(true, {}, appGlobal.recommend[TRID * 1 - 1]);
        var mapIndex = map["Map"];
        var heroModel = window.myHeroList.get(hid);
        var data = heroModel["attributes"];
        for(var m = 0; m < 7; m++) {//7次加点
            var n = m * 3 + 1;
            //每3级加一次 点，从1级开始
            n = n == 19 ? 20 : n;
            //19级没有加点，20级才有

            var index = (data["TIDLV" + n].split(",").indexOf(appGlobal.recommend[TRID*1-1]["LV" + n + "TID"].toString()) + 1).toString();
            var name = appGlobal.talent[appGlobal.recommend[TRID*1-1]["LV"+n+"TID"] - 1]["Name"];
            var icon = "data/Talent/t" + appGlobal.recommend[TRID*1-1]["LV" + n + "TID"] + ".png";
            map["LV" + n + "TID"] = {
                "index" : index,
                "name" : name,
                "icon" : icon
            };
        }
        //改变hid模型的talents
        var talents = heroModel.get("talents");
        talents[mapIndex * 1 - 1] = map;

        heroModel.set({
            talents : talents
        });

        //console.log(heroModel.toJSON());
    }

    this._checkEnable = function() {
        //从服务器检查是否可用
        $.ajax({
            url : getEnableJsonUrl,
            type : "post",
            success : function(data) {
                data = data[HeroesApp.getVersion()] || {
                    "shop" : "true",
                    "talent" : "true"
                };
                appGlobal.enable = data;
                HeroesApp.setConfig("web_shop_enable", data.shop.toString());
                HeroesApp.setConfig("web_talent_enable", data.talent.toString());

                if(appGlobal.enable.shop == "false") {
                    //不是 维修页面，且是shop页面，则刷新
                    if($("#comming_soon").length == 0) {//不是 维修页面
                        if(appGlobal.currentPage == "shop") {//shop页面
                            appGlobal._renderRepairPage();
                        }
                    }

                }
                if(appGlobal.enable.talent == "false") {
                    //不是 维修页面，且是talent页面，则刷新
                    if($("#comming_soon").length == 0) {//不是 维修页面
                        if(appGlobal.currentPage == "talent") {//talent页面
                            appGlobal._renderRepairPage();
                        }
                    }
                }
            },
            dataType : "json"
        })

    }

    this._renderRepairPage = function() {
        //渲染功能修复中的页面
        //alert("_renderRepairPage")
        //关闭所有的模态对话框
        $(".modal.in").removeClass("in").addClass("out");
        $("#mask").addClass("none");

        $("#page").css({
            "background" : "url(img/index_background.jpg) no-repeat"
        });
        $("#main").html("<img id='comming_soon' src=img/comming_soon.png />");
    }

    this._renderFunctionDisabledPage = function() {
        $("#modal_talent_detail").removeClass("in").addClass("out");
        if($(".modal.in").length == 0) {
            $("#mask").addClass("none");
        }

        $("#disabled_mask").fadeIn();
    }

    this._hideFunctionDisabledPage = function() {
        $("#disabled_mask").fadeOut();
    }

}

window.appGlobal = new jsGlobal();

//注意整合的时候，下面 HeroesApp一定要注释！！！！！！！！！！！！
HeroesApp = {
    ready : function() {
        console.log("ready");
        //console.log(appGlobal.talentDefaultJSON);
    },

    gameIsInstalled : function() {
        var flag = true;
        console.log("gameIsInstalled:" + flag);
        return flag;
    },

    browseDirectory : function() {
        console.log("browseDirectory");
    },

    startGame : function() {
        console.log("startGame");
    },
    setMount : function(horseName, index) {
        console.log("setMount:" + horseName + "," + index);
    },
    setTalents : function(json) {
        console.log("setTalent:" + json);
    },
    getConfig : function(key, defaultValue) {
        console.log("getConfig," + key + ":" + defaultValue)
        return defaultValue;
    },
    setConfig : function(key, value) {
        console.log("setConfig," + key + ":" + value)
    },
    startDownload : function() {
        console.log("startDownload");
    },
    update : function() {
        console.log("update");
    },
    getVersion : function() {
        console.log("getVersion");
        return "1.0.0.2";
    }
}

/* 配置文件
 * heroes.ini
 * KEY -> VALUE
 * web_horseId -> int
 * web_color -> string
 * web_horseIndex -> int
 * web_hero -> array<int>
 * web_IsNotFirstTime -> bool/string        //bool/string代表用字符串表示的布尔值，比如 "false"代表假
 * web_enableHorse -> bool/string       //客户端设置
 * web_enableTalent -> bool/string      //客户端设置
 * web_shop_enable -> bool/string       //服务端设置
 * web_talent_enable -> bool/string     //服务端设置
 * web_isFirstTime -> bool/string
 * web_userName -> string
 * web_userFace -> string
 */
